package com.qili.controller.base;

import com.qili.base.controller.BaseController;
import com.qili.core.utils.DictTypes;
import com.qili.core.utils.DictUtil;
import com.qili.entity.base.BaseDict;
import com.qili.service.base.BaseDictService;
import com.qili.util.JsonUtil;
import com.qili.util.ReType;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import tk.mybatis.mapper.entity.Example;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @Author Zhangshuo
 * @date 2020/11/20 19:16
 **/
@Controller
@Slf4j
@RequestMapping("/sys/dict")
public class BaseDictController extends BaseController {
    @Autowired
    BaseDictService baseDictService;

    @ResponseBody
    @RequestMapping(value = "/bytype", method = RequestMethod.GET)
    public ReType getDictByTypeCode(String psTypeCode) {
        ReType re = new ReType();
        try {
            re.setCode(0);
            DictTypes AdtType = DictTypes.getEnumByType(psTypeCode);
            List<BaseDict> AlstTmp = DictUtil.getDictByType(AdtType);
            re.setData(AlstTmp);
        } catch (Exception e) {
            e.printStackTrace();
            re.setCode(1);
            re.setMsg("获取字典数据异常！！" + e.getMessage());
        }
        return re;
    }

    @ResponseBody
    @RequestMapping(value = "/bytypecontain", method = RequestMethod.GET)
    public ReType getDictByTypeCode(String psTypeCode, String keywords) {
        ReType re = new ReType();
        try {
            re.setCode(0);
            DictTypes AdtType = DictTypes.getEnumByType(psTypeCode);
            List<BaseDict> AlstTmp = DictUtil.getDictByType(AdtType, keywords);
            re.setData(AlstTmp);
        } catch (Exception e) {
            e.printStackTrace();
            re.setCode(1);
            re.setMsg("获取字典数据异常！！" + e.getMessage());
        }
        return re;
    }

    @ResponseBody
    @RequestMapping("/getListByTypeCode")
    public ReType getDictList(BaseDict baseDict) {
        ReType reType = new ReType();
        if (baseDict == null) {
            reType.setMsg("查询失败");
        }
        Example example = new Example(BaseDict.class);
        example.and().andEqualTo("badtTypecode",baseDict.getBadtTypecode());
        if(StringUtils.isNotBlank(baseDict.getBadtName())){
            example.and().andLike("badtName","%"+baseDict.getBadtName()+"%");
        }
        List<BaseDict> baseDictList = baseDictService.selectByExample(example);
        reType.setCode(0);
        reType.setData(baseDictList);
        return reType;
    }

    /**
     * 新增字典页面
     * @return
     */
    @ApiOperation(value = "/showAddDict", httpMethod = "GET", notes = "显示新增字典页面")
    @GetMapping(value = "showAddDict")
    @RequiresPermissions("dictName:add")
    public String showAddDict() {
        return "/dict/addDict";
    }

    /**
     * 新增字典
     * @param baseDict
     * @return
     */
    @ResponseBody
    @RequestMapping("/addDictValue")
    @ApiOperation(value = "/addDictValue", httpMethod = "POST", notes = "新增字典")
    @RequiresPermissions("dictName:add")
    public JsonUtil addDictValue(BaseDict baseDict) {
        JsonUtil json = new JsonUtil();
        if (StringUtils.isBlank(baseDict.getBadtTypecode())) {
            json.setFlag(false);
            json.setMsg("未知字典类型编号");
            return json;
        }
        if (StringUtils.isBlank(baseDict.getBadtName())) {
            json.setFlag(false);
            json.setMsg("字典名称不能为空");
            return json;
        }
        if (StringUtils.isBlank(baseDict.getBadtCode())) {
            json.setFlag(false);
            json.setMsg("字典类型不能为空");
            return json;
        }
        JsonUtil jsonUtil = ifExited(baseDict);
        if (!jsonUtil.isFlag()) {
            return jsonUtil;
        }
        baseDictService.insertSelective(baseDict);
        json.setFlag(true);
        return json;
    }

    /**
     * 字典编辑页面
     * @param model
     * @param request
     * @param baseDict
     * @return
     */
    @ApiOperation(value = "/showUpdate", httpMethod = "GET", notes = "显示字典编辑页面")
    @GetMapping(value = "/showUpdate")
    @RequiresPermissions("dictName:edit")
    public String UpdateType(Model model, HttpServletRequest request, BaseDict baseDict) {
        BaseDict baseDict1 = baseDictService.selectByPrimaryKey(baseDict.getBadtNo());
        if (baseDict1 != null) {
            model.addAttribute("baseDict", baseDict1);
        } else {
            throw new RuntimeException("未知的字典id");
        }
        return "/dict/updateDict";
    }


    /**
     * 更新字典
     * @param baseDict
     * @return
     */
    @ApiOperation(value = "/updateDictValue", httpMethod = "POST", notes = "更新字典")
    @PostMapping(value = "/updateDictValue")
    @ResponseBody
    @RequiresPermissions("dictName:edit")
    public JsonUtil updateDictValue(BaseDict baseDict) {
        JsonUtil json = new JsonUtil();
        json.setFlag(false);
        if (baseDict == null) {
            json.setFlag(false);
            json.setMsg("获取数据失败!!!");
            return json;
        }
        BaseDict oldBaseDict = baseDictService.selectByPrimaryKey(baseDict.getBadtNo());
        if (!oldBaseDict.getBadtCode().equals(baseDict.getBadtCode())) {
            //说明编码改了
            BaseDict sameCodeBaseDict = new BaseDict();
            sameCodeBaseDict.setBadtTypecode(oldBaseDict.getBadtTypecode());
            sameCodeBaseDict.setBadtCode(baseDict.getBadtCode());
            JsonUtil jsonUtil = ifExited(sameCodeBaseDict);
            if (!jsonUtil.isFlag()) {
                return jsonUtil;
            }
        }
        if (!oldBaseDict.getBadtName().equals(baseDict.getBadtName())) {
            //说明名称改了
            BaseDict sameNameBaseDict = new BaseDict();
            sameNameBaseDict.setBadtName(baseDict.getBadtName());
            sameNameBaseDict.setBadtTypecode(oldBaseDict.getBadtTypecode());
            JsonUtil jsonUtil = ifExited(sameNameBaseDict);
            if (!jsonUtil.isFlag()) {
                return jsonUtil;
            }
        }
        baseDictService.updateByPrimaryKeySelective(baseDict);
        json.setFlag(true);
        json.setMsg("操作成功");
        return json;
    }

    /**
     * 删除字典
     * @param baseDict
     * @return
     */
    @ResponseBody
    @PostMapping("/deleteDict")
    @ApiOperation(value = "/deleteDict", httpMethod = "POST", notes = "删除字典")
    @RequiresPermissions("dictName:delete")
    public JsonUtil deleteDict(BaseDict baseDict) {
        JsonUtil jsonUtil = new JsonUtil();
        if (baseDict == null) {
            throw new RuntimeException("需要删除的字典数据为null");
        }
        baseDictService.deleteByPrimaryKey(baseDict.getBadtNo());
        jsonUtil.setFlag(true);
        return jsonUtil;
    }

    @ResponseBody
    @PostMapping("/deleteDictByTypeCode")
    @ApiOperation(value = "/deleteDictByTypeCode", httpMethod = "POST", notes = "根据类型删除字典")
    public JsonUtil deleteDictByDictTypeCode(String dictTypeCode) {
        JsonUtil jsonUtil = new JsonUtil();
        if (StringUtils.isBlank(dictTypeCode)) {
            throw new RuntimeException("需要删除的字典类型为空");
        }
        BaseDict dict = new BaseDict();
        dict.setBadtTypecode(dictTypeCode);
        baseDictService.delete(dict);
        jsonUtil.setFlag(true);
        return jsonUtil;
    }


    @ResponseBody
    @RequestMapping("/getDictByBadtCode")
    @ApiOperation(value = "/getDictByBadtCode", httpMethod = "GET", notes = "获取字典")
    public JsonUtil getDictByBadtCode(BaseDict baseDict) {
        JsonUtil jsonUtil = new JsonUtil();
        if (baseDict == null) {
            jsonUtil.setFlag(false);
            jsonUtil.setMsg("未知的查询条件");
            return jsonUtil;
        }
        List<BaseDict> result = baseDictService.select(baseDict);
        if (result.size() > 0) {
            jsonUtil.setData(result.get(0));
            jsonUtil.setFlag(true);
        }
        return jsonUtil;
    }

    /**
     * 判断是否存在,同一种字典类型下,不能同名,不能同编号
     *
     * @param baseDict
     * @return
     */
    public JsonUtil ifExited(BaseDict baseDict) {
        JsonUtil jsonUtil = new JsonUtil();
        BaseDict sameTypeDict = new BaseDict();
        sameTypeDict.setBadtTypecode(baseDict.getBadtTypecode());
        List<BaseDict> thisTypeDict = baseDictService.select(sameTypeDict);
        if (thisTypeDict.size() > 0) {
            for (BaseDict dbBaseDict : thisTypeDict) {
                if (StringUtils.isNotBlank(baseDict.getBadtCode()) && dbBaseDict.getBadtCode().equals(baseDict.getBadtCode())) {
                    jsonUtil.setFlag(false);
                    jsonUtil.setMsg("已经存在的字典编号");
                    return jsonUtil;
                }
                if (StringUtils.isNotBlank(baseDict.getBadtName()) && dbBaseDict.getBadtName().equals(baseDict.getBadtName())) {
                    jsonUtil.setFlag(false);
                    jsonUtil.setMsg("已经存在的字典名称");
                    return jsonUtil;
                }
            }
        }
        jsonUtil.setFlag(true);
        return jsonUtil;
    }


    @ResponseBody
    @RequestMapping("/reloadDict")
    public JsonUtil reloadDict() {
        try {
            DictUtil.loadAllDict();
            return JsonUtil.sucess("字典重新加载成功。");
        } catch (Exception e) {
            e.printStackTrace();
            return JsonUtil.error("字典重新加载失败。" + e.getMessage());
        }
    }

}
